package redisinit

import (
	"cartsrv/cartrpc"
	"context"
	"fmt"
	"strconv"
)

func AddCart(userId, goodsId, goodsNum int, goodsTitle, goodsCover string, goodsPrice float32) error {
	key := fmt.Sprintf("cart:user_id_%d:goods_id_%d", userId, goodsId)
	return RedisClient.HMSet(context.Background(), key, map[string]interface{}{
		"goodsId":    goodsId,
		"goodsNum":   goodsNum,
		"goodsTitle": goodsTitle,
		"goodsCover": goodsCover,
		"goodsPrice": goodsPrice,
		"Checked":    1,
	}).Err()
}
func ListCart(userId int) (cartInfo []*cartrpc.CarItem, err error) {
	key := fmt.Sprintf("cart:user_id_%d:*", userId)
	keys := RedisClient.Keys(context.Background(), key).Val()
	for _, v := range keys {
		goodsInfo := RedisClient.HGetAll(context.Background(), v).Val()
		goodsId, _ := strconv.Atoi(goodsInfo["goodsId"])
		goodsNum, _ := strconv.Atoi(goodsInfo["goodsNum"])
		goodsTitle := goodsInfo["goodsTitle"]
		Checked, _ := strconv.Atoi(goodsInfo["Checked"])
		goodsPrice, _ := strconv.ParseFloat(goodsInfo["goodsPrice"], 64)
		cartInfo = append(cartInfo, &cartrpc.CarItem{
			UserId:     int64(userId),
			GoodsId:    int64(goodsId),
			GoodsTitle: goodsTitle,
			GoodsNum:   int64(goodsNum),
			Checked:    int64(Checked),
			GoodsPrice: float32(goodsPrice),
		})
	}
	return
}
func SyncGoodsStock(goodsId, goodsStock int64) {
	key := fmt.Sprintf("goods_stock:goods_id_%d", goodsId)
	for i := 0; i < int(goodsStock); i++ {
		RedisClient.RPush(context.Background(), key, goodsId)
	}
}
